from django.core.management.base import NoArgsCommand
from django.db import transaction
from django.test import Client
from stream import models, recommendations, views, forms
from stream.selenium import selenium

class Provider:
    """
    A mock for feed finding and retrieving
    """
    def __init__(self, path, suffix, url_template):
        import os
        data_files = os.listdir(path)
        self.data = {}
        self.usernames = set()
        for filename in data_files:
            pos = filename.find('.' + suffix)
            if pos != -1:
                username = filename[:pos]
                self.usernames.add(username)
                self.data[url_template % username] = open(os.path.join(path, filename)).read()

    def retrieve(self, url):
        return self.data[url]

class Command(NoArgsCommand):
    @transaction.commit_on_success
    def handle_noargs(self, **options):
        provider = Provider('stream/testcases/data/recommendations', 'json', 'http://feeds.delicious.com/v2/json/%s?count=100')
        models.DeliciousChannel.retrieveUrl.mock(provider.retrieve)
        models.DeliciousChannel.DEFAULT_ENTRY_LOAD = 100
        for username in provider.usernames:
            current_user = models.User.objects.create_user(username, '', 'password')
            print 'Inserting', username
            client = Client()
            assert client.login(username = username, password = 'password'), 'Username is %s' % username
            response = client.post('/add', { 'form_name' : forms.DeliciousForm.FORM_NAME, 'author' : username }, follow = True)
            if response.status_code != 200:
                print username, response.status_code
            models.Message.objects.filter(user = current_user).update(published = True)
